package com.llg.service;

import com.llg.model.BoxSizeVO;
import com.llg.model.BoxVO;
import com.llg.model.code.CommonCode;
import com.llg.model.response.DataResult;
import com.llg.model.response.PageResult;
import com.llg.model.response.ResponseResult;
import com.llg.pojo.BoxPO;
import com.llg.pojo.BoxSizePO;
import com.llg.repository.BoxPORepository;
import com.llg.repository.BoxSizePORepository;
import com.llg.util.ConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BoxService {

    private final BoxPORepository boxPORepository;
    private final BoxSizePORepository boxSizePORepository;

    @Autowired
    public BoxService(BoxPORepository boxPORepository, BoxSizePORepository boxSizePORepository) {
        this.boxPORepository = boxPORepository;
        this.boxSizePORepository = boxSizePORepository;
    }

    public PageResult<BoxVO> findAll() {
        List<BoxPO> all = boxPORepository.findAll();
        List<BoxVO> boxVOList = ConvertUtils.povoListConvert(all, BoxVO.class);
        for (BoxVO boxVO : boxVOList) {
            List<BoxSizePO> boxSizePOList = boxSizePORepository.findAllByBoxId(boxVO.getId());
            List<BoxSizeVO> boxSizeVOList = ConvertUtils.povoListConvert(boxSizePOList, BoxSizeVO.class);
            boxVO.setBoxSizeList(boxSizeVOList);
        }
        return new PageResult<>(CommonCode.SUCCESS, boxVOList.size(), 1, boxVOList);
    }


    public DataResult<BoxVO> add(BoxVO boxVO) {
        BoxPO boxPO = ConvertUtils.povoConvert(boxVO, BoxPO.class);
        BoxPO save = boxPORepository.save(boxPO);
        return new DataResult<>(CommonCode.SUCCESS, ConvertUtils.povoConvert(save, BoxVO.class));
    }

    public ResponseResult delete(int id) {
        boxPORepository.deleteById(id);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    public ResponseResult update(BoxVO boxVO) {
        Optional<BoxPO> optional = boxPORepository.findById(boxVO.getId());
        if (optional.isPresent()) {
            BoxPO boxPO = optional.get();
            BeanUtils.copyProperties(boxVO, boxPO);
            BoxPO save = boxPORepository.save(boxPO);
            return new DataResult<>(CommonCode.SUCCESS, ConvertUtils.povoConvert(save, BoxVO.class));
        }
        return new ResponseResult(CommonCode.NO_EXIST_ID);
    }

    public DataResult<BoxVO> findOne(int id) {
        Optional<BoxPO> optional = boxPORepository.findById(id);
        if (optional.isPresent()) {
            BoxPO po = optional.get();
            BoxVO boxPO = ConvertUtils.povoConvert(po, BoxVO.class);
            return new DataResult<>(CommonCode.SUCCESS, boxPO);
        }

        return new DataResult<>(CommonCode.NO_EXIST_ID, null);
    }
}
